<!DOCTYPE html>
<html class="x-admin-sm">
<head>
    {include file="../tpl/header.html" /}
</head>
<body>
<h3 style="font-size:30px; padding: 15px">普通文件上传示例:</h3>
<div class="layui-fluid">
    <div class="layui-row">
        <form class="layui-form" method="post" action="">
            <div class="layui-form-item">
                <label class="layui-form-label">普通文件上传</label>
                <div class="layui-input-inline">
                    <input type="text" placeholder="" name="img" required="" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-btn">上传图片</label>
                <input class="layui-btn" type="file" id="file" name="file" style="width: 84px;left: 315px;position: absolute;cursor: pointer;opacity: 0;"/>
            </div>
        </form>
    </div>
</div>
<hr />
<h3 style="font-size:30px; padding: 15px">大文件上传示例:</h3>
<div class="layui-fluid">
    <div class="layui-row">
        <form class="layui-form" method="post" action="" onsubmit="return false;">

            <div class="layui-form-item">
                <label class="layui-form-label">保存的文件名</label>
                <div class="layui-input-inline">
                    <input type="text" placeholder="" name="save" required="" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux">
                    <span class="x-red">*</span>为了防止重名,系统会默认在保存文件名前添加随机参数
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">选择上传文件</label>
                <div class="layui-input-inline">
                    <input id="big-file" type="file" placeholder="" name="file" required="" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-mid layui-word-aux">
                    <span class="x-red">*</span>上传过程中发生错误,请重新刷新该页面进行上传
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">进度条</label>
                <div class="layui-input-inline" style="margin-top: 10px;">
                    <div class="layui-progress layui-progress-big" lay-showPercent="yes">
                        <div class="layui-progress-bar layui-bg-green" lay-percent="0%"></div>
                    </div>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">简介</label>
                <div class="layui-input-block">
                    <textarea placeholder="文件简介" id="introduce" name="introduce" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">链接</label>
                <div class="layui-input-block">
                    <textarea placeholder="上传完成之后,下载链接显示在此处" id="upload_url" class="layui-textarea"></textarea>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <button class="layui-btn" lay-filter="add" onclick="fire();" lay-submit="">上传</button>
            </div>

        </form>
    </div>
</div>
</body>
<script>
    //普通文件 - 上传
    $('#file').change(function(){
        var files = this.files;
        var file = files[0];
        var url = "{:url('admin/index/upload')}";
        var data = upload(file,'file',url);
        console.log(data);
        $('input[name=img]').val(data.url);
    });


    //大文件 - 上传
    var xhr = new XMLHttpRequest();
    var clock = null;
    var save = '';
    var upload_url = '';

    function now_time() {
        var date = new Date();
        date.setTime(date.getTime());
        console.log(date.setTime(date.getTime()));
        return 't'+date.getHours()+date.getMinutes()+date.getSeconds();
    }
    function fire(){
        //初始化参数
        $('#upload_url').val('');
        document.getElementsByClassName('layui-progress-bar')[0].style.width = '0%';
        document.getElementsByClassName('layui-progress-bar')[0].setAttribute('lay-percent','0%');



        save = $('input[name=save]').val();
        if(save === ''){
            layer.msg('请填写要保存的文件名', {icon: 5,time: layer_msg_error_time});
            return;
        }
        if(save.indexOf('.') === -1){
            layer.msg('请填写正确的文件名', {icon: 5,time: layer_msg_error_time});
            return;
        }
        var file_info = save.split('.');
        if(file_info[file_info.length - 1] === ''){
            layer.msg('保存的文件名后缀不能为空', {icon: 5,time: layer_msg_error_time});
            return;
        }
        save = now_time() + save;
        clock = window.setInterval(upfile,1000); //每一秒触发一次upfile函数
    }
    var upfile = (function(){
        const LENGTH = 1024 * 1024; //定义每一次分割的文件的大小,单位:字节
        var start = 0;
        var end = start + LENGTH;
        var fd = null;
        var flag = false; //flag标志当前是否有文件在上传中
        var percent = 0;
        return (function(){
            /*如果有文件在上传则不进行操作,因为上次没传完就开始下次时会导致合并的文件衔接不上*/
            if(flag){
                return;
            }
            var file = document.getElementById('big-file').files[0];
            if(start > file.size){ //所有分块上传完成跳出函数清除计数器
                clearInterval(clock);
                console.log(upload_url);
                $('#upload_url').val(upload_url.url);
                start = 0;
                fd = null;
                flag = false;
                percent = 0;
                add_log();
                return;
            }
            bloba = file.slice(start,end);
            fd = new FormData();
            fd.append('file',bloba);
            fd.append('save',save);
            fd.append('big',1);
            up(fd);
            /*监听上传过程,定时器触发upfile函数时若是flag为true则不进行操作以免文件上传合并的时候出问题*/
            xhr.upload.onprogress = function(ev){
                if(ev.loaded < LENGTH){
                    flag = true;
                }
            }
            percent = 100 * end / file.size;
            if(percent > 100){
                percent = 100;
            }
            percent = percent.toFixed(2);
            document.getElementsByClassName('layui-progress-bar')[0].style.width = percent + '%';
            document.getElementsByClassName('layui-progress-bar')[0].setAttribute('lay-percent',percent + '%');
            document.getElementsByClassName('layui-progress-text')[0].innerHTML = percent + '%';
            start = end;
            end = start + LENGTH ;
            flag = false; //当前分块上传完成,flag置false

        });
    })();
    function up(fd){
        //采用同步上传防止文件写入时顺序出错
        xhr.open('POST','{:url("admin/index/upload")}',false);
        xhr.setRequestHeader("X-Requested-With",'XMLHttpRequest');
        xhr.onreadystatechange = function(){
            if (xhr.readyState === 4){
                if (xhr.status === 200 || xhr.status === 304){
                    var info = JSON.parse(xhr.responseText);
                    if(info.code !== 1){
                        clearInterval(clock);
                        layer.alert(info.msg);
                    }else{
                        upload_url = info.data;
                    }
                }
            }
        }
        xhr.send(fd);
    }

    //提交日志
    function add_log() {
        var url = $('#upload_url').val();
        var introduce = $('#introduce').val();
        $.ajax({
            type:'post',
            url:"{:url('admin/admin/uploadLog')}",
            data:{"url":url,"introduce":introduce},
            dataType:'json',
            async:true,
            success:function (e) {
                console.log(e)
            }
        })
    }

</script>
</html>